from rest_framework import permissions, filters, response
from rest_framework.decorators import action
from apps.basic.environment.models import EnvironmentModel
from apps.basic.environment.serializers import EnvironmentModelSerializer, EnvironmentNamesModelSerializer
from utils import viewsets
from utils.response import data_response


class EnvironmentViewSet(viewsets.MyViewSets):
    queryset = EnvironmentModel.objects.all()
    serializer_class = EnvironmentModelSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.OrderingFilter]
    ordering_fields = ['create_time']

    @action(methods=["GET"], detail=False)
    def names(self, request, *args, **kwargs):
        serializer = self.get_serializer(instance=self.get_queryset().filter(is_delete=0), many=True)
        result = data_response(data=serializer.data)
        return response.Response(result)

    def get_serializer_class(self):
        if self.action == "names":
            return EnvironmentNamesModelSerializer
        else:
            return self.serializer_class
